package algorithm.moore_select;

/**
 * 摩尔投票法解决众数问题
 * @author yuisama
 * @date 2022/04/12 17:10
 **/
public class Num169_MajorityElement {
    public int majorityElement(int[] nums) {
        int candidate = nums[0];
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == candidate) {
                count ++;
            }else {
                count --;
                if (count == 0) {
                    // 更换候选人
                    candidate = nums[i];
                    count = 1;
                }
            }
        }
        return candidate;
    }
}